package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.utils.threadlocal.AppThreadLocalUtils;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @ClassName ApUserSearchServiceImpl
 * @Description TODO
 * @Author AWei
 * @DATE 2021/4/25 21:34
 * @Version 1.0
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Resource
    private BehaviorFeign behaviorFeign;

    @Resource
    MongoTemplate mongoTemplate;

    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDto userSearchDto) {
        // 1. 参数校验：用户ID、搜索词
        Integer userId = userSearchDto.getEntryId();
        String searchWords = userSearchDto.getSearchWords();
        if (ObjectUtils.isEmpty(userId) || StringUtils.isBlank(searchWords)) {
            log.error("记录用户搜索历史失败,参数错误 用户ID：{}，搜索词: {}", userId, searchWords);
            return;
        }
        // 2. 根据用户ID字段查询行为实体数据
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(userId, null);
        if (ObjectUtils.isEmpty(behaviorEntry)) {
            log.error("用户关联的行为实体数据未找到,参数错误 用户ID：{}，搜索词: {}", userId, searchWords);
            return;
        }
        // 3. 查询是否保存过该搜索词
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                .and("keyword").is(userSearchDto.getSearchWords())
        ), ApUserSearch.class);
        // 3.1 保存过  更新时间字段
        if (userSearch != null) {
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
        } else {
            // 3.2 未保存过  添加该搜索词
            userSearch = new ApUserSearch();
            userSearch.setEntryId(behaviorEntry.getId());
            userSearch.setKeyword(userSearchDto.getSearchWords());
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
        }
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {
        //1. 获取当前登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (ObjectUtils.isEmpty(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2. 获取行为实体
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), userSearchDto.getEquipmentId());
        if (ObjectUtils.isEmpty(behaviorEntry)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户行为实体不存在");
        }
        //3. 设置查询条件：行为实体ID、分页为10、创建时间降序排序
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(10);
        List<ApUserSearch> userSearchList = mongoTemplate.find(query, ApUserSearch.class);
        //4. 返回结果
        return ResponseResult.okResult(userSearchList);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        // 1. 判断ID值是否存在
        if (ObjectUtils.isEmpty(dto.getId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (ObjectUtils.isEmpty(user)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 获取行为实体
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (ObjectUtils.isEmpty(behaviorEntry)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户行为实体不存在");
        }
        //3. 根据ID和行为实体ID,删除搜索历史记录
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("_id").is(dto.getId()));
        mongoTemplate.remove(query, ApUserSearch.class);
        return ResponseResult.okResult();
    }
}

